package com.yjt.fresh.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.AuthResult;
import com.yjt.fresh.MainActivity;
import com.yjt.fresh.MyApp;
import com.yjt.fresh.PayResult;
import com.yjt.fresh.R;
import com.yjt.fresh.api.ApiAliPay;
import com.yjt.fresh.api.ApiPayByRestMoney;
import com.yjt.fresh.api.ApiWeiXinPay;
import com.yjt.fresh.base.BaseSimpleActivity;
import com.yjt.fresh.bean.BeanOrderResult;
import com.yjt.fresh.bean.BeanWeiXinResult;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.utils.TimeUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 支付页面
 * Created by mcc on 2018/8/2.
 */

public class AtyPay extends BaseSimpleActivity {
    private static final int ALI_PAY = 1006;
    private static final int WEI_XIN_PAY = 1007;
    private static final int REST_MONEY_PAY = 1008;
    private static final int OFFLINE_PAY = 1009;
    @BindView(R.id.back)
    RelativeLayout mBack;
    @BindView(R.id.tvAppAtyPayNeedMoney)
    TextView mTvNeedMoney;
    @BindView(R.id.llAppAtyPayOffWeiXinPay)
    LinearLayout mLlWeiXinPay;
    @BindView(R.id.llAppAtyPayAliPay)
    LinearLayout mLlAliPay;
    @BindView(R.id.llAppAtyPayOffBankPay)
    LinearLayout mLlBankPay;
    @BindView(R.id.llAppAtyPayOffLinePay)
    LinearLayout mLlOffLinePay;
    @BindView(R.id.tvAppAtyPayToPay)
    TextView mTvToPay;
    @BindView(R.id.ivAppAtyPayWeiXinPay)
    ImageView mIvWeiXinPay;
    @BindView(R.id.ivAppAtyPayAli)
    ImageView mIvAli;
    @BindView(R.id.ivAppAtyPayBank)
    ImageView mIvBank;
    @BindView(R.id.ivAppAtyPayOffline)
    ImageView mIvOffline;
    @BindView(R.id.tvAppAtyPayRestMoney)
    TextView mTvRestMoney;
    private IWXAPI iwxapi;
    private BeanWeiXinResult mWeiXinResult;
    private BeanOrderResult mBeanOrderResult;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private double mOrderMoney;
    private String mFromWhere;
    private int mPayWay = WEI_XIN_PAY;
    private String mOrderID;
    private String mDatePoor;

    @Override
    protected int getContentView() {
        return R.layout.app_aty_pay;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        MyApp.addActivity(this);//添加activity 用于finish使用
        mOrderMoney = getIntent().getDoubleExtra(MyConstants.ORDER_MONEY, 0);
        mBeanOrderResult = (BeanOrderResult) getIntent().getSerializableExtra(MyConstants.ORDER_INFO);
        mFromWhere = getIntent().getStringExtra(MyConstants.FROM_WHERE);
        mOrderID = getIntent().getStringExtra(MyConstants.ORDER_ID);
        String deadTime = getIntent().getStringExtra(MyConstants.DEAD_TIME);
        Date deadDate = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if (MyConstants.BALANCE.equals(mFromWhere)) {
            try {
                deadDate = format.parse(mBeanOrderResult.getDEADLINE());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else if (MyConstants.MY_ORDER.equals(mFromWhere)) {
            try {
                deadDate = format.parse(deadTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        Date currentDate = new Date(System.currentTimeMillis());
        mDatePoor = TimeUtils.getDatePoor(deadDate, currentDate);
        mTvNeedMoney.setText(mOrderMoney + "");
        mTvRestMoney.setText("余额支付("+PreferenceManager.getInstance().getRestMoney()+"元)");

    }

    @Override
    protected void initEvent() {


        mLlAliPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPayWay = ALI_PAY;
                mIvAli.setImageResource(R.mipmap.a2_icon_01);
                mIvBank.setImageResource(R.mipmap.a2_icon_02);
                mIvWeiXinPay.setImageResource(R.mipmap.a2_icon_02);
                mIvOffline.setImageResource(R.mipmap.a2_icon_02);
            }
        });

        mLlWeiXinPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPayWay = WEI_XIN_PAY;

                mIvAli.setImageResource(R.mipmap.a2_icon_02);
                mIvBank.setImageResource(R.mipmap.a2_icon_02);
                mIvWeiXinPay.setImageResource(R.mipmap.a2_icon_01);
                mIvOffline.setImageResource(R.mipmap.a2_icon_02);
            }
        });

        mLlBankPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPayWay = REST_MONEY_PAY;

                mIvAli.setImageResource(R.mipmap.a2_icon_02);
                mIvBank.setImageResource(R.mipmap.a2_icon_01);
                mIvWeiXinPay.setImageResource(R.mipmap.a2_icon_02);
                mIvOffline.setImageResource(R.mipmap.a2_icon_02);
            }
        });

        mLlOffLinePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPayWay = OFFLINE_PAY;

                mIvAli.setImageResource(R.mipmap.a2_icon_02);
                mIvBank.setImageResource(R.mipmap.a2_icon_02);
                mIvWeiXinPay.setImageResource(R.mipmap.a2_icon_02);
                mIvOffline.setImageResource(R.mipmap.a2_icon_01);
            }
        });
        mTvToPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (mPayWay) {
                    case ALI_PAY:
                        aliPay();
                        break;
                    case WEI_XIN_PAY:
                        weiXinPay();
                        break;
                    case REST_MONEY_PAY:
                        restMoneyPay();
                        break;
                    case OFFLINE_PAY:
                        offlinePay();
                        break;
                }
            }
        });

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backDialog();
            }
        });

        //判断余额是否足够支付,需要在点击事件之后处理 不然无效
        if (PreferenceManager.getInstance().getRestMoney() >= mOrderMoney){

        }else {
            mLlBankPay.setClickable(false);
        }
    }

    @Override
    public void onBackPressed() {
        backDialog();
    }

    private void isSureRestMoneyPay(){
        final Dialog dialog = new Dialog(mContext, R.style.MyDialog);
        dialog.setContentView(R.layout.app_dialog_sure_cancel);
        TextView tvTitle = dialog.findViewById(R.id.tvAppDIalogSureCancelTitle);
        TextView tvContent = dialog.findViewById(R.id.tvAppDIalogSureCancelContent);
        TextView tvCancel = dialog.findViewById(R.id.tvAppDialogSureCancelCancel);
        TextView tvSure = dialog.findViewById(R.id.tvAppDialogSureCancelSure);
        tvTitle.setVisibility(View.VISIBLE);
        tvTitle.setText("确认使用余额支付吗?");
        tvCancel.setTextColor(getResources().getColor(R.color.color_0076ff));
        tvCancel.setText("确定支付");
        tvSure.setText("取消支付");
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }

            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                restMoneyPay();
            }
        });
        dialog.show();
    }
    private void backDialog() {
        final Dialog dialog = new Dialog(mContext, R.style.MyDialog);
        dialog.setContentView(R.layout.app_dialog_sure_cancel);
        TextView tvTitle = dialog.findViewById(R.id.tvAppDIalogSureCancelTitle);
        TextView tvContent = dialog.findViewById(R.id.tvAppDIalogSureCancelContent);
        TextView tvCancel = dialog.findViewById(R.id.tvAppDialogSureCancelCancel);
        TextView tvSure = dialog.findViewById(R.id.tvAppDialogSureCancelSure);
        tvTitle.setVisibility(View.VISIBLE);
        tvTitle.setText("确认取消支付吗?");
        tvContent.setText("您的订单在" + mDatePoor + "内未支付将被取消，请尽快完成支付。");
        tvCancel.setTextColor(getResources().getColor(R.color.color_0076ff));
        tvCancel.setText("继续支付");
        tvSure.setText("取消支付");
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }

            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Intent intent = new Intent(mContext, MainActivity.class);
                startActivity(intent);
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialog.show();
    }

    private void offlinePay() {

    }

    private void restMoneyPay() {
        ApiPayByRestMoney apiPayByRestMoney = new ApiPayByRestMoney(new HttpOnNextListener<BaseResultEntity>() {
            @Override
            public void onNext(BaseResultEntity baseResultEntity) {
                Intent intent = new Intent(mContext, AtyPayResult.class);
                intent.putExtra(MyConstants.PAY_RESULT, MyConstants.SUCCESS);
                startActivity(intent);
                finish();
            }

            @Override
            public void onReLogin() {

            }
        },mContext,true,false,false);
        Map<String, Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        if (MyConstants.BALANCE.equals(mFromWhere)) {
            map.put("UNIONPAYNO", mBeanOrderResult.getUNIONPAYNO());
        } else if (MyConstants.MY_ORDER.equals(mFromWhere)) {
            map.put("ORDERS_ID", mOrderID);
        }

        apiPayByRestMoney.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiPayByRestMoney);
    }

    private void weiXinPay() {
        ApiWeiXinPay apiWeiXinPay = new ApiWeiXinPay(new HttpOnNextListener<BeanWeiXinResult>() {

            @Override
            public void onNext(BeanWeiXinResult beanWeiXinResult) {
                if (beanWeiXinResult != null) {
                    mWeiXinResult = beanWeiXinResult;
                    toWXPay();
                }
            }

            @Override
            public void onReLogin() {

            }
        }, mContext, true, false, false);

        Map<String, Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        if (MyConstants.BALANCE.equals(mFromWhere)) {
            map.put("UNIONPAYNO", mBeanOrderResult.getUNIONPAYNO());
        } else if (MyConstants.MY_ORDER.equals(mFromWhere)) {
            map.put("ORDERS_ID", mOrderID);
        }

        apiWeiXinPay.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiWeiXinPay);

    }

    private void aliPay() {
        ApiAliPay apiAliPay = new ApiAliPay(new HttpOnNextListener<String>() {

            @Override
            public void onNext(String s) {
                payV2(s);
            }

            @Override
            public void onReLogin() {

            }
        }, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        if (MyConstants.BALANCE.equals(mFromWhere)) {
            map.put("UNIONPAYNO", mBeanOrderResult.getUNIONPAYNO());
        } else if (MyConstants.MY_ORDER.equals(mFromWhere)) {
            map.put("ORDERS_ID", mOrderID);
        }
        apiAliPay.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiAliPay);

    }

    @Override
    protected void onResume() {
        super.onResume();
        int wxPayResult = PreferenceManager.getInstance().getWXPayResult();
        if (wxPayResult != 110) {
            if (wxPayResult == 0) {
                PreferenceManager.getInstance().setWXPayResult(110);
                Intent intent = new Intent(mContext, AtyPayResult.class);
                intent.putExtra(MyConstants.PAY_RESULT, MyConstants.SUCCESS);
                startActivity(intent);
                finish();
            } else {
                PreferenceManager.getInstance().setWXPayResult(110);
                Intent intent = new Intent(mContext, AtyPayResult.class);
                intent.putExtra(MyConstants.PAY_RESULT, MyConstants.FAIL);
                startActivity(intent);
            }
        }
    }

    private void toWXPay() {
        iwxapi = WXAPIFactory.createWXAPI(this, null); //初始化微信api
        iwxapi.registerApp(mWeiXinResult.getAppid()); //注册appid  appid可以在开发平台获取

        Runnable payRunnable = new Runnable() {  //这里注意要放在子线程
            @Override
            public void run() {
                PayReq request = new PayReq(); //调起微信APP的对象
                //下面是设置必要的参数，也就是前面说的参数,这几个参数从何而来请看上面说明
                request.appId = mWeiXinResult.getAppid();
                request.partnerId = mWeiXinResult.getPartnerid();
                request.prepayId = mWeiXinResult.getPrepayid();
                request.packageValue = "Sign=WXPay";
                request.nonceStr = mWeiXinResult.getNoncestr();
                request.timeStamp = mWeiXinResult.getTimestamp();
                request.sign = mWeiXinResult.getSign();
                iwxapi.sendReq(request);//发送调起微信的请求
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 支付宝支付业务
     */
    public void payV2(final String orderInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(AtyPay.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if ("9000".equals(resultStatus)) {

                        Intent intent = new Intent(mContext, AtyPayResult.class);
                        intent.putExtra(MyConstants.PAY_RESULT, MyConstants.SUCCESS);
                        startActivity(intent);
                        finish();
                    } else {
                        Intent intent = new Intent(mContext, AtyPayResult.class);
                        intent.putExtra(MyConstants.PAY_RESULT, MyConstants.FAIL);
                        startActivity(intent);
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档

                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


}
